package demo.DataStrucAndAlgo.Stack;

import java.util.Scanner;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/7/25-07-25-19:57
 * @Description：demo.DataStrucAndAlgo.Stack
 */
class ONode{
    int data;
    ONode next;

    public ONode(int data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ONode{" +
                "data=" + data +
                '}';
    }
}
class ONode_Stack{          //单链表，有头结点，即第一个结点为top.next
    ONode top = new ONode(0);
    public void push(int data){     //压栈   利用头插法 （便于遍历）

        ONode newNode = new ONode(data);
        newNode.next = top.next;       //先将之前的头结点改为第二个结点
        top.next = newNode;       //修改头结点
    }
    public int pop(){      //弹栈     从top.next弹出
        if(top.next == null){
            throw new RuntimeException("空栈");
        }
        ONode temp = top.next;      //取出弹出的结点
        top.next = top.next.next;     //弹出结点
        System.out.println(temp.data);
        return temp.data;     //返回弹出结点值
    }
    public void show(){
        ONode temp = top;
        while (temp.next != null){     //从头结点top.next开始遍历输出
            System.out.println(temp.next);
            temp = temp.next;
        }
    }
}
public class Stack_OneLinked {
    public static void main(String[] args) {
        ONode_Stack stack = new ONode_Stack();
        char key = ' ';//用户输入
        boolean flag = true;//循环判据
        Scanner scanner = new Scanner(System.in);
        while (flag) {
            System.out.println("s(show):打印栈");
            System.out.println("p(push):压栈");
            System.out.println("g(pop):出栈");
            System.out.println("e(exit):退出程序");
            key = scanner.next().charAt(0);
            switch (key) {
                case 's':
                    stack.show();
                    break;
                case 'p':
                    System.out.print("请输入数据：");
                    stack.push(scanner.nextInt());
                    break;
                case 'g':
                    stack.pop();
                    break;
                case 'e':
                    flag = false;
                    break;
            }
        }
        scanner.close();
    }

}

